package com.yonyou.gmmc.common.eventhandler;

import org.marketing.common.dto.EventDataDTO;
import org.marketing.common.event.BizEvent;
import org.marketing.common.event.HandleResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


@Component
public abstract class AbstractEventHandler {

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	

	protected String backInfo = "";

	public String getBackInfo() {
		return backInfo;
	}

	/**
	 * 具体的业务描述
	 * 
	 * @return
	 */
	protected abstract String getHandleInfo();

	/**
	 * 预处理数据
	 * 
	 * @param event
	 * @return
	 */
	protected abstract EventDataDTO preTransform(BizEvent event);

	/**
	 * 具体处理的逻辑
	 * 
	 * @param event
	 * @return
	 */
	protected abstract boolean handle(EventDataDTO data);

	/**
	 * 处理完成后进行的逻辑判断
	 */
	protected abstract  void afterPay(BizEvent event);
	
	
	/**
	 * 判断是否要处理，目前用于过滤重复发送过来的事件
	 * 
	 * @param event
	 * @return
	 */
	protected abstract boolean preCheck(BizEvent event);
	
	/**
	 * 事件处理
	 * 
	 * @param event
	 * @return
	 */
	public HandleResult handleing(BizEvent event) {
		logger.info(this.getClass().getName()+"开始处理事件，对应处理的逻辑为【" + this.getHandleInfo() + "】");

		HandleResult handleResult = new HandleResult();
		
		try {
			if(!preCheck(event)){
				handleResult.setHandle(true);
				handleResult.setProcess(false);
				handleResult.setMessage("事件准入判断跳过");//返回的消息
				return handleResult;
			}
			
			EventDataDTO o = this.preTransform(event);//预处理 转换业务对象
			handleResult.setHandle(true);
			handleResult.setProcess(handle(o));
			handleResult.setMessage(getBackInfo());//返回的消息
			//新增事件处理记录
			afterPay(event);
		} catch (Exception e) {
			logger.error("处理事件失败，异常" + e);
			handleResult.setHandle(false);
			handleResult.setProcess(false);
			handleResult.setMessage(getBackInfo());
		}

		return handleResult;

	}

}
